package com.njmd.framework.utils;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;

public class StringUtil {
	/**
	 * 获取到两个字符串中相同的部分
	 * @param s1
	 * @param s2
	 * @return
	 */
	public static String getSameSubString(String s1, String s2) {
		if (s1.length() > s2.length()) {
			String temp = s1;
			s1 = s2;
			s2 = temp;
		}
		int n = s1.length();
		int index = 0;
		ok: for (; n > 0; n--) {
			for (int i = 0; i < s1.length() - n + 1; i++) {
				String s = s1.substring(i, i + n);
				if (s2.indexOf(s) != -1) {
					index = i;
					break ok;
				}
			}
		}
		return s1.substring(index, index + n);
	}
	
	/** 
     * 生成数据文件 
     *  
     * @param filePath 写入文件的路径 
     * @param content 写入的字符串内容 
     * @return 
     */  
    public static  boolean string2File(String content, String filePath) {  
        boolean flag = true;  
        BufferedReader bufferedReader=null;
        BufferedWriter bufferedWriter =null;
        
        try {  
            File file = new File(filePath);  
            if (!file.exists()) {  
                file.createNewFile();  
            }  
            bufferedReader = new BufferedReader(new StringReader(content));  
            bufferedWriter = new BufferedWriter(new FileWriter(file));  
            char buffer[] = new char[1024];  
            int len;  
            while ((len = bufferedReader.read(buffer)) != -1) {  
                bufferedWriter.write(buffer, 0, len);  
            }  
            bufferedWriter.flush();  
            bufferedReader.close();  
            bufferedWriter.close();  
        } catch (IOException e) {  
            flag = false;  
            return flag;  
        } finally {  
            if (bufferedReader != null) {  
                try {  
                    bufferedReader.close();  
                } catch (IOException e) {  
                }  
            }  
        }  
        return flag;  
    }  
	
	public static void main(String[] args) {
		String sameParentTreeCode=getSameSubString(",1,20,", ",1,22,");
		
		if(!sameParentTreeCode.endsWith(","))
			sameParentTreeCode=sameParentTreeCode.substring(0, sameParentTreeCode.lastIndexOf(","));
		
		String[] tmps=sameParentTreeCode.split(",");
		for(int i=tmps.length-1;i>0;i--){
			if(tmps[i].length()>0){
				sameParentTreeCode=tmps[i];
				break;
			}
		}
		System.out.println(sameParentTreeCode);
	}
	
	/**
	 * 将分钟转换为N小时M分钟
	 * 
	 * @param minute
	 * @return
	 */
	public static String formatMinute(Long minute)
	{
		long hour = minute / 60;
		long min = minute % 60;
		if(hour==0)
			return min + "分钟";
		else
			return  hour + "小时" + min + "分钟";
	}
}
